<template>
  <view class="basement">
    <uni-forms ref="form" :value="formData" label-position="top">
      <uni-forms-item v-if="formData.auditType == 2" label="请假类型 :" name="name" label-position="left">
        <uni-data-select v-model="formData.leaveType" :localdata="leaveList"></uni-data-select>
      </uni-forms-item>
      <uni-forms-item v-if="formData.auditType == 3" label="加班类型 :" name="name" label-position="left">
        <uni-data-select v-model="formData.overtimeType" :localdata="overTimeList"></uni-data-select>
      </uni-forms-item>
      </uni-forms-item>

      <!-- 补卡1-->
      <view v-if='formData.auditType == 1'>
        <uni-forms-item label="补卡时间:" name="name">
          <uni-datetime-picker :border='false' v-model="formData.replacementDate" placeholder="请选择补卡时间" />
        </uni-forms-item>
      </view>
      <!-- 请假 2-->
      <view v-if='formData.auditType == 2'>
        <uni-forms-item label="开始时间:" name="name">
          <uni-datetime-picker :border='false' @change='changeLeaveStart' v-model="formData.startTime" type='date'
            placeholder="请选择开始时间" />
          <uni-data-select v-model="formData.startType" @change='changeStartType'
            :localdata="timeList"></uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="结束时间:" name="name">
          <uni-datetime-picker :border='false' @change='changeLeaveEnd' v-model="formData.endTime" type='date'
            placeholder="请选择结束时间" />
          <uni-data-select v-model="formData.endType" @change='changeEndType' :localdata="timeList"></uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="请假时长(天)"  label-width="200" name="name">
          <uni-easyinput type="text" :disabled="true" v-model="formData.duration" placeholder="请输入请假时长" />
        </uni-forms-item>

      </view>

      <!-- 加班 3 -->
      <view v-if='formData.auditType == 3'>
        <uni-forms-item label="开始时间:" name="name">
          <uni-datetime-picker :border='false' @change='changeOverStart' v-model="formData.startTime"
            placeholder="请选择开始时间" />
        </uni-forms-item>
        <uni-forms-item label="结束时间:" name="name">
          <uni-datetime-picker :border='false' @change='changeOverEnd' v-model="formData.endTime"
            placeholder="请选择结束时间" />
        </uni-forms-item>
        <uni-forms-item label="吃饭开始时间:" label-width="200" name="name">
          <uni-datetime-picker :border='false' @change='changeEatStart' v-model="formData.eatStartTime"
            placeholder="请选择吃饭开始时间" />
        </uni-forms-item>

        <uni-forms-item label="吃饭时长" label-width="200" name="name">
          <uni-data-select v-model="formData.eatDuration" :localdata="eatList"
            @change="changeEatDuration"></uni-data-select>
        </uni-forms-item>

        <uni-forms-item label="吃饭结束时间:" label-width="200" name="name">
          <uni-datetime-picker :disabled="true" :border='false' v-model="formData.eatEndTime" placeholder="请选择吃饭结束时间" />
        </uni-forms-item>
        <uni-forms-item label="加班时长(小时)" label-width="200" name="name">
          <uni-easyinput type="text" :disabled="true" v-model="formData.duration" />
        </uni-forms-item>
      </view>

      <uni-forms-item label="事由:" name="email">
        <uni-easyinput type="textarea" v-model="formData.causeOfMatter" placeholder="请填写事由信息" />
      </uni-forms-item>

      <uni-forms-item label="附件 :" name="name">
        <view>
          <uni-file-picker fileMediatype="image" @delete="onDelete" @select="onSelect" :value="fileList"
            :image-styles="imageStyles" />
        </view>
      </uni-forms-item>

      </uni-forms-item>
      <button @click="submit" type="primary" class="submitBtn">提交</button>
    </uni-forms>
  </view>
</template>

<script>
  import {
    LEAVE_LIST
  } from '../../constants/constants'
  import {
    getUserInfo,
    messageSuccess
  } from '../../utils'
  import {
    applyAudit
  } from '../../utils/api'
  import uploadFile from '../../utils/upload'
  export default {
    data() {
      return {
        fileList: [],
        overTimeList: [{
          value: 1,
          text: '串休加班'
        }, {
          value: 2,
          text: '加班费加班'
        }],
        id: '',
        form: "",
        dataList: "", //假期类型
        title: '',
        formData: {
          startType: '上午',
          endType: '上午'
        },
        leaveList: LEAVE_LIST,
        timeList: [{
          value: '上午',
          text: '上午'
        }, {
          value: '下午',
          text: '下午'
        }],
        eatList: [{
          value: '0',
          text: '0分钟'
        },{
          value: '0.25',
          text: '15分钟'
        }, {
          value: '0.5',
          text: '30分钟'
        }, {
          value: '0.75',
          text: '45分钟'
        }, {
          value: '1',
          text: '60分钟'
        }],
        imageStyles: {
          width: 98,
          height: 98,
          border: {
            width: 2,
            style: 'dashed',
            radius: '2px'
          }
        },
      }
    },
    onLoad: function(option) {
      const userInfo = getUserInfo()
      this.formData.auditType = +option.id
      this.formData.userId = userInfo.userId
      uni.setNavigationBarTitle({
        title: option.title
      })
    },
    methods: {
      changeLeaveStart() {
        if (this.formData.endTime) {
          this.diffLeave(this.formData.startTime, this.formData.endTime)
        }
      },
      changeLeaveEnd() {
        if (this.formData.startTime) {
          this.diffLeave(this.formData.startTime, this.formData.endTime)
        }
      },
      changeStartType() {
        if (this.formData.startTime && this.formData.endTime) {
          this.diffLeave(this.formData.startTime, this.formData.endTime)
        }
      },
      changeEndType() {
        if (this.formData.startTime && this.formData.endTime) {
          this.diffLeave(this.formData.startTime, this.formData.endTime)
        }
      },
      diffLeave(start, end) {
        const sdate = new Date(start.replaceAll('-', '/')).getTime()
        const now = new Date(end.replaceAll('-', '/')).getTime()
        const days = now - sdate
        if (days < 0) {
          return uni.showToast({
            icon: 'none',
            title: '开始时间不能大于结束时间'
          })
        }
        let day = parseInt(days / (1000 * 60 * 60 * 24));
        if (now == sdate) {
          if (this.formData.startType == this.formData.endType) {
            day += 0.5
          } else {
            day += 1
          }

        } else if (
          this.formData.startType == this.formData.endType
        ) {
          day = day + 0.5;
        } else {
          day = day + 1;
        }
        this.formData.duration = day
      },
      changeOverStart() {
        if (this.formData.endTime) {
          this.diffOvertime(this.formData.startTime, this.formData.endTime)
        }
      },
      changeOverEnd() {
        if (this.formData.startTime) {
          this.diffOvertime(this.formData.startTime, this.formData.endTime)
        }
      },
      changeEatStart() {
        this.calcEatEndTime()
      },
      changeEatDuration() {
        this.calcEatEndTime()
        if (this.formData.startTime && this.formData.endTime) {
          this.diffOvertime(this.formData.startTime, this.formData.endTime)
        }
      },
      calcEatEndTime() {
        // 计算吃饭结束时间
        if (this.formData.eatStartTime && this.formData.eatDuration) {
          const duration = this.formData.eatDuration * 60 * 60 * 1000
          const start = +new Date(this.formData.eatStartTime)
          let date = new Date(parseInt(duration + start))
          let Year = date.getFullYear()
          let Moth =
            date.getMonth() + 1 < 10 ?
            "0" + (date.getMonth() + 1) :
            date.getMonth() + 1
          let Day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
          let Hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
          let Minute =
            date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()
          let Sechond =
            date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()
          let GMT =
            Year +
            "-" +
            Moth +
            "-" +
            Day +
            " " +
            Hour +
            ":" +
            Minute +
            ":" +
            Sechond
          this.formData.eatEndTime = GMT
        }
      },
      diffOvertime(start, end) {
        const startTime = new Date(start);
        const endTime = new Date(end);
        if (startTime > endTime) {
          return uni.showToast({
            icon: 'none',
            title: '开始时间不能大于结束时间'
          })
        }
        let timeInterval = endTime - startTime;
        let hours = timeInterval / (1000 * 60 * 60);
        let roundedHours = Math.round(hours * 4) / 4;
        this.formData.duration = roundedHours - (this.formData.eatDuration || 0)
      },
      async submit() {
        const params = {
          ...this.formData
        }
        // 请假
        if (this.formData.auditType == 2) {
          if (!this.formData.startTime || !this.formData.endTime || !this.formData.leaveType) {
            return uni.showToast({
              title: '请填写正确信息',
              icon: 'none'
            })
          }
          params.startTime += ` ${this.formData.startType}`
          params.endTime += ` ${this.formData.endType}`
        }
        // 补卡
        if (this.formData.auditType == 1) {
          if (!this.formData.replacementDate) {
            return uni.showToast({
              title: '请填写正确信息',
              icon: 'none'
            })
          }
        }
        // 加班
        if (this.formData.auditType == 3) {
          if (!this.formData.startTime || !this.formData.endTime || !this.formData.eatDuration || !this.formData
            .eatEndTime) {
            return uni.showToast({
              title: '请填写正确信息',
              icon: 'none'
            })
          }
          if (this.formData.startTime.slice(0, 10) !== this.formData.endTime.slice(0, 10)) {
            return uni.showToast({
              title: '加班开始时间和结束时间不是同一天',
              icon: 'none',
              duration: 3000
            })
          }
        }
        // 上传图片
        let file = []
        if (this.fileList.length) {
          const list = []
          for (let i = 0; i < this.fileList.length; i++) {
            list.push(uploadFile(this.fileList[i]))
          }
          const res = await Promise.all(list)
          res.forEach(item => {
            file.push(item.data.fileUrl.replace('/home/appserver/attachments',
              'https://oa.tasystem-bj.online:8901/attach'))
          })
        }
        if (file.length) {
          params.attaUrl = file.join(',')
        }
        // // 上传数据
        await applyAudit(params)
        messageSuccess('提交成功', () => {
          uni.navigateBack()
        })
      },

      onDelete() {
        this.fileList = []
      },
      onSelect(e) {
        this.fileList.push(e.tempFiles[0])
      },

    }
  }
</script>

<style scoped>
  .basement {
    width: 100%;
    height: 100%;
    padding: 30upx;
    box-sizing: border-box;
  }

  /* input {
		border: 0;
		border-color: #fff;
	} */
  /deep/ .uni-forms-item__inner {
    padding: 0;
    margin: 0;
    border-bottom: 1px solid #eee;
  }

  /deep/.uni-forms-item__content {
    display: flex;
    align-items: center;

  }

  .rules {
    width: 100%;
    display: flex;
    color: #ccc;
    justify-content: space-between;
    align-items: center;
  }

  .submitBtn {
    margin-top: 18px;
  }
</style>